/*
 * Copyright 2011-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.mgmt.commons.util;

/**
 * IP 工具类.
 *
 * @author liym
 * @since 2021-04-04 22:34 新建
 */
public final class IPUtils {

    private IPUtils() {
        throw new AssertionError("No instance!");
    }

    /**
     * 将 IPv4 地址转换成十进制数值IP
     *
     * @param ipv4 IPv4
     * @return 十进制数值IP
     */
    public static long toLong(String ipv4) {
        String[] ipParts = ipv4.split("\\.");
        long ip = 0L;
        for (String part : ipParts) {
            ip = Long.parseLong(part) | ip << 8L;
        }
        return ip;
    }

    /**
     * 将十进制数值IP转换成IPv4地址
     *
     * @param ip 十进制数值IP
     * @return IPv4
     */
    public static String toIPv4(long ip) {
        return (ip >> 24) + "."
                + ((ip & 0x00FFFFFF) >> 16) + "."
                + ((ip & 0x0000FFFF) >> 8) + "."
                + (ip & 0x000000FF);
    }

}
